<?php
/**
 * Here is your custom functions.
 */

if (!function_exists('create_uuid')) {
    /**
     * 创建UUID,系统内唯一标识符
     * @return string
     */
    function create_uuid()
    {
        mt_srand((float)microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtolower(md5(uniqid(rand(), true)));
        $hyphen = chr(45); // "-"
        $uuid = substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12);
        return $uuid;
    }
}

if (!function_exists('create_noncestr')) {
    /**
     *  产生随机字符串，默认32位
     */
    function create_noncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}

if (!function_exists('is_administrator')) {
    /**
     * 检测当前用户是否为管理员
     * @return boolean true-管理员，false-非管理员
     */
    function is_administrator($uid = null)
    {
        $uid = is_null($uid) ? is_login() : $uid;
        return $uid && (intval($uid) === config('system.USER_ADMINISTRATOR'));
    }
}

if (!function_exists('list_to_tree')) {
    /**
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('tree_to_list')) {
    /**
     * 将list_to_tree的树还原成列表
     * @param array $tree 原来的树
     * @param string $child 孩子节点的键
     * @param string $order 排序显示的键，一般是主键 升序排列
     * @param array $list 过渡用的中间数组，
     * @return array        返回排过序的列表数组
     */
    function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array())
    {
        if (is_array($tree)) {
            $refer = array();
            foreach ($tree as $key => $value) {
                $reffer = $value;
                if (isset($reffer[$child])) {
                    unset($reffer[$child]);
                    tree_to_list($value[$child], $child, $order, $list);
                }
                $list[] = $reffer;
            }
            $list = list_sort_by($list, $order, $sortby = 'asc');
        }
        return $list;
    }
}

if (!function_exists('list_sort_by')) {
    /**
     * 对查询结果集进行排序
     * @access public
     * @param array $list 查询结果
     * @param string $field 排序的字段名
     * @param array $sortby 排序类型
     * asc正向排序 desc逆向排序 nat自然排序
     * @return array
     */
    function list_sort_by($list, $field, $sortby = 'asc')
    {
        if (is_array($list)) {
            $refer = $resultSet = array();
            foreach ($list as $i => $data)
                $refer[$i] = &$data[$field];
            switch ($sortby) {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc':// 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
            }
            foreach ($refer as $key => $val)
                $resultSet[] = &$list[$key];
            return $resultSet;
        }
        return false;
    }
}

if (!function_exists('ucenter_encrypt_md5')) {
    /**
     * 系统非常规MD5加密方法
     * @param string $str 要加密的字符串
     * @return string
     */
    function ucenter_encrypt_md5($str, $key = 'ThinkUCenter')
    {
        return '' === $str ? '' : md5(sha1($str) . $key);
    }
}


if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @return mixed
     */
    function get_client_ip($type = 0)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) return $ip[$type];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}

if (!function_exists('data_auth_sign')) {
    /**
     * 数据签名认证
     * @param array $data 被认证的数据
     * @return string       签名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function data_auth_sign($data)
    {
        //数据类型检测
        if (!is_array($data)) {
            $data = (array)$data;
        }
        ksort($data); //排序
        $code = http_build_query($data); //url编码并生成query字符串
        $sign = sha1($code); //生成签名
        return $sign;
    }
}

if (!function_exists('curl_post')) {
    /**
     * 使用post json形式请求
     * @param $url
     * @param $header
     * @param $content
     * @return bool|string
     */
    function curl_post($url, $header, $content)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
        $response = curl_exec($ch);
        if ($error = curl_error($ch)) {
            die($error);
        }
        curl_close($ch);
        return $response;
    }
}


if (!function_exists('object2array')) {
    /**
     * 对象转数组
     * @param $array
     * @return array
     */
    function object2array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = object2array($value);
            }
        }
        return $array;
    }
}

if (!function_exists('yuanToFen')) {
    /**
     * 元转分
     * @param $yuan
     * @return int
     */
    function yuanToFen($yuan)
    {
        $yuanCut = explode('.', $yuan);
        if (count($yuanCut) == 1) return intval($yuanCut[0] . '00');
        if (strlen($yuanCut[1]) == 1) return intval($yuanCut[0] . $yuanCut[1] . '0');
        if (strlen($yuanCut[1]) == 2) return intval($yuanCut[0] . $yuanCut[1]);
        if (strlen($yuanCut[1]) > 2) return intval($yuanCut[0] . substr($yuanCut[1], 0, 2));
    }
}

if (!function_exists('fenToYuan')) {
    /**
     * 分转元
     * @param $fen
     * @return float
     */
    function fenToYuan($fen)
    {
        if (strlen($fen) == 1) return floatval('0.0' . $fen);
        if (strlen($fen) == 2) return floatval('0.' . $fen);
        $yuanPart = substr($fen, 0, strlen($fen) - 2);
        $fenPart = substr($fen, -2);
        return floatval($yuanPart . '.' . $fenPart);
    }
}

if (!function_exists('createOrderNumber')) {
    /**
     * 创建业务单号
     * @return string
     */
    function createProcessingNumber()
    {
        return getTimeStamp('YmdHisu') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('getTimeStamp')) {
    /**
     * 创建时间
     * 使用方法：getTimeStamp('Y-m-d H:i:s:u')
     * @param string $format
     * @param null $utimestamp
     * @return false|string
     */
    function getTimeStamp($format = 'Y-m-d H:i:s:u', $utimestamp = null)
    {
        if (is_null($utimestamp)) {
            $utimestamp = microtime(true);
        }

        $timestamp = floor($utimestamp);
        $milliseconds = round((1 + $utimestamp - $timestamp) * 1000);

        return date(preg_replace('`(?<!\\\\)u`', substr(strval($milliseconds), 1, 3), $format), $timestamp);
    }
}